package com.effectiv.gooruda.business.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import jodd.util.StringUtil;
import lombok.extern.log4j.Log4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.effectiv.gooruda.business.api.AbstractBusinessService;
import com.effectiv.gooruda.business.api.ApplicationService;
import com.effectiv.gooruda.domain.Application;
import com.effectiv.gooruda.domain.SocialProvider;

import com.effectiv.gooruda.repository.ApplicationRepository;

@Log4j
@Service
public class ApplicationServiceImpl extends
		AbstractBusinessService<Application, String> implements
		ApplicationService {

	@Autowired
	private ApplicationRepository repository;

	@Override
	public void save(Application t) {
		t.setPrivateKey(UUID.randomUUID().toString());
		t.setPublicKey(UUID.randomUUID().toString());
		
		
		super.save(t);
	}

	public List<Application> findByTenantCompany() {
		
		List<Application> applications = null;
		if(isTenantCompanyAdmin()){
			applications = repository.findByTenantCompany(getTenantCompany());
		}
		
		
		return applications;

	}

	@Override
	protected void initInternal() {
		setRepository(repository);
	}

	@Override
	public Application updateKey(String id, String type) {
		Application app = findOne(id);
		if (StringUtil.equals("pub", type)) {
			app.setPublicKey(UUID.randomUUID().toString());
		} else if (StringUtil.equals("pvt", type)) {
			app.setPrivateKey(UUID.randomUUID().toString());
		}

		super.update(app);

		return app;
	}

	@Override
	public Application addSocialProvider(String appId, SocialProvider provider) {
		Application app = findOne(appId);

		List<SocialProvider> socialProviders = app.getSocialProviders();

		if (socialProviders == null) {
			socialProviders = new ArrayList<SocialProvider>();
		}

		socialProviders.add(provider);
		app.setSocialProviders(socialProviders);
		super.update(app);

		return app;
	}

	@Override
	public Application findByPublicKey(String key) {
		
		return repository.findByPublicKey(key);
	}

}
